perl hash operations

169

perl hash operations -

# Basic syntax:
my %your_hash = (
	key_1 => "value_1",
    key_2 => "value_2",
    key_3 => "value_3",
);
# Where:
#	- The % is used to denote a hash
#	- key:value pairs are denoted with key => "value" syntax

Add a key:value pair to a hash:
$your_hash{new_key} = "new_value"

# Remove a key:value pair from a hash:
delete $your_hash{key_1}

# Access a specific value from a hash:
my %fruit_color = (
  apple  => "red",
  banana => "yellow",
);
print "$fruit_color{'apple'}\n";
--> Red

# All of the keys or values that exist in a hash can be accessed using
# the "keys" and "values" functions. Here we assign the results to arrays:
my @fruits = keys %fruit_color;
my @colors = values %fruit_color;

# It's possible to iterate through keys (or values) with a foreach loop: 
foreach my $fruit (keys %fruit_color) {  
    print "$fruit\n";  
}
--> apple
--> banana

# Check if hash contains a particular key:
if (exists $fruit_color{orange}) {print "The hash contains orange\n"} 

Comments

Submit
0 Comments